package me.zhanshi123.invitelink;

import com.google.gson.Gson;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class AdBroadcastTask extends BukkitRunnable {
    @Override
    public void run() {
        final Advertisement advertisement = fetchAd();
        new BukkitRunnable() {
            @Override
            public void run() {
                Bukkit.getConsoleSender().sendMessage("§6§lInviteLink §7>>> §r" + advertisement.getContents());
            }
        }.runTaskLater(Main.getInstance(), 50L);
    }

    public Advertisement fetchAd() {
        try {
            URL url = new URL("http://www.zhanshi123.me/ad/index.php");
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String json = br.readLine();
            return new Gson().fromJson(json, Advertisement.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
